package edu.ccut.saturn.manager.dict.core;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IDataDictTypeInfo;
import edu.ccut.saturn.component.IDictItemInfo;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnDictionaryManager;

public class DeleteDictParam extends DefaultComponent {

	private static final String DELETE_DICTPARAM_SQL = "DELETE FROM saturn_dict WHERE type = ? and code = ?";

	@SuppressWarnings("unchecked")
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		String codes = (String) parameterContext.getParameterValue(0);
		String type = (String) parameterContext.getParameterValue(1);

		String delSucc = "false";
		List<String> codeList = this.codeList(codes);
		List<IDictItemInfo> removeList = new ArrayList<IDictItemInfo>();

		PreparedStatement statement = null;
		ResultSet rs = null;

		try {
			for (String dictcode : codeList) {
				statement = parameterContext.getConnection().prepareStatement(
						DELETE_DICTPARAM_SQL);

				statement.setString(1, type);
				statement.setString(2, dictcode);

				statement.executeUpdate();

				IDictItemInfo deleteItem = SaturnDictionaryManager.getInstance()
						.getDataDictItemInfo(type, dictcode);

				removeList.add(deleteItem);
			}

			if (removeList != null) {
				delSucc = "true";
			}

		} catch (Exception e) {
			logger.error("found exception when execute Component Node "
					+ this.getComponentFullKey(), e);
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (statement != null) {
				statement.close();
			}
		}

		if ("true".equals(delSucc)) {
			IDataDictTypeInfo dataDictTypeInfo = SaturnDictionaryManager
					.getInstance().getDataDictTypeInfo(type);

			List<IDictItemInfo> dictItemList = dataDictTypeInfo.getItems();

			if (removeList.size() > 0) {
				dictItemList.removeAll(removeList);
			}
		}

		parameterContext.setParameter(2, delSucc);
	}

	private List<String> codeList(String keys) {

		List<String> codeList = new ArrayList<String>();
		String[] codeArray = keys.split(",");

		for (String code : codeArray) {
			codeList.add(code);
		}

		return codeList;
	}
}
